package com.alawn.security.service.impl;

import com.alawn.framework.services.enums.ResourceType;
import com.alawn.framework.services.security.Resource;
import com.alawn.framework.services.system.Dictionary;
import com.alawn.security.mapper.ResourceMapper;
import com.alawn.security.service.ResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 资源表 服务实现类
 * </p>
 *
 * @author johnny
 * @since 2019-02-27
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

    @Override
    public TreeNode treeDataModel(Resource selected, ResourceType... filter) {
        List<Resource> resources = this.list();
        TreeNode root = new DefaultTreeNode(new Resource(), null);
        setTreeLeaf(root, resources, selected, filter);
        return root;
    }

    @Override
    public TreeNode treeDataModel(ResourceType... filter) {
        return treeDataModel(null, filter);
    }


    @Override
    public List<Resource> createButtons(List<Dictionary> dictionaries) {
        List<Resource> buttons = new ArrayList<>();
        dictionaries.forEach(dict -> {
            Resource button = new Resource(ResourceType.BUTTON);
            button.setName(dict.getName());
            button.setCode(dict.getCode());
            button.setSeq(dict.getSeq());
            buttons.add(button);
        });
        return buttons;
    }

    private void setTreeLeaf(TreeNode root, List<Resource> resources, Resource selected, ResourceType... filter) {
        root.setExpanded(true);
        root.setSelected(root.getData() != null && root.getData().equals(selected));
        Iterator<Resource> iterator = new ArrayList<>(resources).iterator();
        while (iterator.hasNext()) {
            Resource resource = iterator.next();
            if (resource.isChildren((Resource) root.getData()) && !Arrays.asList(filter).contains(resource.getType())) {
                iterator.remove();
                TreeNode node = new DefaultTreeNode(resource, root);
                setTreeLeaf(node, resources, selected, filter);
            }
        }
    }





}
